package com.lihaichen.utils.http.poc.stackoverflow;

import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

/**
 *
 * @url http://stackoverflow.com/questions/5976092/how-to-do-request-in-httpclient
 * 
 */
public class URLSample {

    private static int TIMEOUT=300;

    private static String mIpAddress = "localhost";
    private static int mPort =8080;
    private static String mSubPage ="CalculatorApp/CalculatorWSService";

    public static void main(String[] args) {

        HttpURLConnection conn = null;
        try {
            // The formated URL will be "http://www.androidcoder.org:80".
            URL url = new URL(String.format("http://%s:%d/%s", mIpAddress, mPort, mSubPage));

            System.out.println("call url:"+url);
            
            conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-length", "0");
            conn.setUseCaches(false);
            conn.setAllowUserInteraction(false);
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);

            // NOTE: Below is used to perform the http authentication.
            // It is working in JAVA but not
            // always working in Android platform.

            // Set to use the default HTTP authentication.
            // Working in JAVA, but not working in
            // Android.
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("user1", "pass1".toCharArray());
                }
            });
            conn.connect();

            System.out.println(conn.getResponseCode()); // <-- The request will stop here if running
            // in Android.
            System.out.println(conn.getResponseMessage());

            printOutput(conn);

        } catch (MalformedURLException e) {
            // TODO: Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // Operation timed out.
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

    }

    /**
     * @brief print the output of the HTTP connection.
     * @param conn [in] Http connection.
     */
    private static void printOutput(HttpURLConnection conn) throws IOException {
        int length = 256;
        byte bytes[] = new byte[length];
        InputStream is = conn.getInputStream();

        while (is.available() > 0) {

            if (is.available() < length) {
                length = is.available();
            }

            conn.getInputStream().read(bytes, 0, length);
            System.out.println(bytes);
        }
    }
}
